//
//  InfoCenterController.m
//  HarmonizePub
//
//  Created by rzhy on 2017/3/2.
//  Copyright © 2017年 rzhy. All rights reserved.
//

#import "InfoCenterController.h"
#import "Config.h"
#import "Utils.h"
#import "User.h"
#import "ChangeNameController.h"
#import "ChangePwdController.h"
#import "JPUSHService.h"

static CGFloat const cellHeight = 50.0f;

@interface InfoCenterController () <UITableViewDataSource, UITableViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, ChangeNameControllerDelegate>
{
    NSString *_pushState;
    User *_user;
    UIImageView *_imageView;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *loginOutButton;

@end

@implementation InfoCenterController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"个人中心";
    self.loginOutButton.layer.cornerRadius = 5.0f;
    self.loginOutButton.layer.masksToBounds = YES;
    _user = [NSKeyedUnarchiver unarchiveObjectWithFile:XHUserPath];
    self.tableView.contentInset = UIEdgeInsetsMake(16.0, 0, 0, 0);
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
    _pushState = UIUserNotificationTypeNone == setting.types ? @"已关闭" : @"已开启";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 退出登录
- (IBAction)logOffEvent {
    if (_user) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提 示:" message:@"是否确认要退出登录?" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        __weak typeof(self) weakSelf = self;
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"退出" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            NSString *token = [UserDefaultsTool stringForKey:XHToken];
            NSDictionary *cookie = @{CookieVaule : token};
            [HTTPSTool POSTRequestWithPath:XHLoginOut cookie:cookie params:nil success:^(NSDictionary * _Nonnull JSON) {
//                XHLog(@"退出登录 -> JSON: %@", JSON)
            }];
            
            [JPUSHService setTags:nil alias:@"" fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias) {
//                XHLog(@"退出清空别名 -> iResCode: %d, iTags: %@, iAlias: %@", iResCode, iTags, iAlias);
            }];
            [ZYFileManager deleteFinderAndFileWithPath:XHUserPath];
            [ZYFileManager deleteFinderAndFileWithPath:XHPatientListPath];
            [ZYFileManager deleteFinderAndFileWithPath:[ZYFileManager getDocumentDirectoryWithFileName:XHHeadImageName]];
            [UserDefaultsTool setObject:@"0" forKey:XHToken];
            [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
            [UserDefaultsTool setObject:@(0) forKey:XHNewMessage];
            [[NSNotificationCenter defaultCenter] postNotificationName:XHNewMessage object:nil];
            [ZYToast showOperationSuccess];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:sureAction];
        [self presentViewController:alertController animated:YES completion:nil];
    } else {
        [self setAlertViewWithMessage:@"您还未登录，无需退出登录!"];
    }
}

#pragma mark - 头像
- (UIImageView *)createHeadImage {
    if (!_imageView) {
        _imageView = [[UIImageView alloc] init];
        _imageView.layer.cornerRadius = 5.0f;
        _imageView.layer.masksToBounds = YES;
        _imageView.image = [UIImage imageNamed:@"default_avatar.png"];
        _imageView.frame = (CGRect){CGPointZero, 64.0, 64.0};
        [_imageView downloadImageWithURLString:_user.icon placeholderString:@"default_avatar.png"];
    }
    return _imageView;
}

- (UILabel *)createAttributedLabelWithText:(NSString *)text {
    NSMutableParagraphStyle *muParagraph = [[NSMutableParagraphStyle alloc] init];
    muParagraph.firstLineHeadIndent = 16.0f;
    NSDictionary *attributes = @{
                                 NSFontAttributeName : [UIFont systemFontOfSize:15.0f],
                                 NSParagraphStyleAttributeName : muParagraph
                                 };
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:text attributes:attributes];
    
    UILabel *label = [[UILabel alloc] init];
    label.frame = (CGRect){CGPointZero, XHScreenWidth, 24.0f};
    label.attributedText = attributedString;
    return label;
}

#pragma mark - tableView delegate/dataSource Method
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger count = 4;
    return count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) return 80.0f;
    return cellHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    switch (indexPath.row) {
        case 0: { // 头像
            cell.accessoryView = [self createHeadImage];
            cell.textLabel.text = @"头　　像";
        }
            break;
        case 1: { // 真实姓名
            cell.textLabel.text = @"真实姓名";
            cell.detailTextLabel.text = _user.name;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
            break;
        case 2: { // 修改密码
            cell.textLabel.text = @"修改密码";
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
            break;
        case 3: { // 消息通知
            cell.textLabel.text = @"消息通知";
            cell.detailTextLabel.text = _pushState;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
            break;
        default:
            break;
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 24.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [self createAttributedLabelWithText:@"请在iPhone的 \"设置\" - \"通知\" 中修改。"];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    switch (indexPath.row) {
        case 0: // 头像
            [self setHeadImage];
            break;
        case 1: // 真实姓名
            [self setName];
            break;
        case 2: // 修改密码
            [self changePassword];
            break;
        case 3: { // 消息通知
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication] canOpenURL:url])
                [[UIApplication sharedApplication] openURL:url];
        }
            break;
        default:
            break;
    }
}

#pragma mark - 头像
- (void)setHeadImage {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    __weak typeof(self) weakSelf = self;
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf createImagePickerWithType:1];
    }];
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"从手机相册获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf createImagePickerWithType:0];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:cameraAction];
    [alertController addAction:albumAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark imagePicker
- (void)createImagePickerWithType:(NSInteger)type {
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    if (type) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    } else {
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    [self presentViewController:imagePicker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    [self performSelector:@selector(uploadImageFileWithImage:) withObject:image afterDelay:0.5];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)uploadImageFileWithImage:(UIImage *)image {
    NSString *token = [UserDefaultsTool stringForKey:XHToken];
    NSString *path = [NSString stringWithFormat:@"%@?%@", XHUploadHeadImage, token];
    __weak typeof(self) weakSelf = self;
    [HTTPSTool uploadFileWithURLString:path params:nil constructingBodyBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *imageData = UIImageJPEGRepresentation(image, 0.3);
        if (imageData)
            [formData appendPartWithFileData:imageData name:XHHeadImageName fileName:XHHeadImageName mimeType:@".jpg"];
    } success:^(NSDictionary * _Nonnull JSON) {
//        XHLog(@"上传头像 -> JSON:%@", JSON)
        _imageView.image = image;
        [ZYToast showOperationSuccess];
        [weakSelf getUserInfo];
    }];
    
}

#pragma mark - 真实姓名
- (void)setName {
    ChangeNameController *changeName = [[ChangeNameController alloc] init];
    changeName.delegate = self;
    [self.navigationController pushViewController:changeName animated:YES];
}

- (void)changeName:(ChangeNameController *)changeName changeNameWithName:(NSString *)name {
    _user.name = name;
    [_tableView reloadData];
    [self getUserInfo];
}

#pragma mark - 修改密码
- (void)changePassword {
    ChangePwdController *changePwd = [[ChangePwdController alloc] init];
    [self.navigationController pushViewController:changePwd animated:YES];
}

#pragma mark - 获取用户信息
- (void)getUserInfo {
    NSDictionary *cookie = @{CookieVaule : [UserDefaultsTool stringForKey:XHToken]};
    [HTTPSTool POSTRequestWithPath:XHGetUserInfo cookie:cookie params:nil success:^(NSDictionary * _Nonnull JSON) {
//        XHLog(@"获取用户信息 -> JSON: %@", JSON)
        NSDictionary *userDict = JSON[@"data"][@"user"];
        _user.name       = userDict[@"name"];
        _user.sex       = userDict[@"sex"];
        _user.icon       = userDict[@"headImage"];
        _user.userName   = userDict[@"userName"];
        _user.token      = userDict[@"token"];
        _user.createDate = userDict[@"createDate"];
        _user.identifier = userDict[@"id"];
        _user.deviceType = userDict[@"deviceType"];
        _user.userType   = userDict[@"userType"];
        [NSKeyedArchiver archiveRootObject:_user toFile:XHUserPath];
    }];
}

#pragma mark - AlertView
- (void)setAlertViewWithMessage:(NSString *)message {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提 示:" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:defaultAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

@end
